
import React, { useState, useEffect, useCallback } from "react";
import { GlobalEvent } from "@/entities/GlobalEvent";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Plus, Calendar, Clock, AlertCircle } from "lucide-react";
import { useToast } from "@/components/ui/use-toast";

import GlobalEventForm from "../global-events/GlobalEventForm";
import GlobalEventCard from "../global-events/GlobalEventCard";

export default function GlobalEventsManager() {
  const [events, setEvents] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editingEvent, setEditingEvent] = useState(null);
  const { toast } = useToast();

  const loadEvents = useCallback(async () => {
    setIsLoading(true);
    try {
      const fetchedEvents = await GlobalEvent.list("-start_date");
      setEvents(Array.isArray(fetchedEvents) ? fetchedEvents : []);
    } catch (error) {
      console.error("加载全局事件失败:", error);
      toast({
        variant: "destructive",
        title: "加载失败",
        description: "无法加载全局事件数据"
      });
      setEvents([]);
    }
    setIsLoading(false);
  }, [toast]);

  useEffect(() => {
    loadEvents();
  }, [loadEvents]);

  const handleSubmit = async (eventData) => {
    try {
      if (editingEvent) {
        await GlobalEvent.update(editingEvent.id, eventData);
        toast({
          title: "更新成功",
          description: "全局事件已更新"
        });
      } else {
        await GlobalEvent.create(eventData);
        toast({
          title: "创建成功", 
          description: "全局事件已创建"
        });
      }
      setShowForm(false);
      setEditingEvent(null);
      await loadEvents();
    } catch (error) {
      console.error("保存事件失败:", error);
      toast({
        variant: "destructive",
        title: "保存失败",
        description: error.message || "未知错误"
      });
    }
  };

  const handleEdit = (event) => {
    setEditingEvent(event);
    setShowForm(true);
  };

  const handleDelete = async (eventId) => {
    if (window.confirm("确定要删除此全局事件吗？")) {
      try {
        await GlobalEvent.delete(eventId);
        toast({
          title: "删除成功",
          description: "全局事件已删除"
        });
        await loadEvents();
      } catch (error) {
        console.error("删除事件失败:", error);
        toast({
          variant: "destructive",
          title: "删除失败",
          description: error.message || "未知错误"
        });
      }
    }
  };

  const handleCancel = () => {
    setShowForm(false);
    setEditingEvent(null);
  };

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h3 className="text-xl font-semibold">全局事件管理</h3>
          <p className="text-gray-600 mt-1">管理影响施工计划的全局时间窗口和特殊事件</p>
        </div>
        <Button
          onClick={() => setShowForm(true)}
          className="bg-blue-600 hover:bg-blue-700"
        >
          <Plus className="w-4 h-4 mr-2" />
          添加事件
        </Button>
      </div>

      {showForm && (
        <GlobalEventForm
          event={editingEvent}
          onSubmit={handleSubmit}
          onCancel={handleCancel}
        />
      )}

      <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
        {isLoading ? (
          Array(6).fill(0).map((_, i) => (
            <Card key={i} className="animate-pulse">
              <CardHeader>
                <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                <div className="h-3 bg-gray-200 rounded w-1/2"></div>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  <div className="h-3 bg-gray-200 rounded"></div>
                  <div className="h-3 bg-gray-200 rounded w-2/3"></div>
                </div>
              </CardContent>
            </Card>
          ))
        ) : events.length === 0 ? (
          <div className="col-span-full">
            <Card className="text-center py-12">
              <CardContent>
                <Calendar className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                <h3 className="text-lg font-semibold text-gray-900 mb-2">
                  暂无全局事件
                </h3>
                <p className="text-gray-500 mb-6">
                  创建您的第一个全局事件来管理特殊时间窗口
                </p>
                <Button
                  onClick={() => setShowForm(true)}
                  className="bg-blue-600 hover:bg-blue-700"
                >
                  <Plus className="w-4 h-4 mr-2" />
                  添加事件
                </Button>
              </CardContent>
            </Card>
          </div>
        ) : (
          events.map((event) => (
            <GlobalEventCard
              key={event.id}
              event={event}
              onEdit={handleEdit}
              onDelete={handleDelete}
            />
          ))
        )}
      </div>
    </div>
  );
}
